﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Tulde.Core;
using System.IO.IsolatedStorage;
using System.IO;

namespace Tulde.MP3tunes
{
    public class IsolatedStorageLogProvider : ILogProvider
    {
        private static object _synchLock = new object();
        enum Mode
        {
            Debug,
            Info,
            Warn,
            Error
        }
        private const string LOG_FILE = "app.log";
        private IsolatedStorageFile fileStore;
        private StreamWriter sw;
        #region ILogProvider Members

        public void Initialize()
        {
            //lock (_synchLock)
            //{
            //    if (fileStore != null)
            //    {
            //        fileStore.Dispose();
            //        fileStore = null;
            //    }

            //    fileStore = IsolatedStorageFile.GetUserStoreForApplication();
            //    sw = new StreamWriter(fileStore.OpenFile(LOG_FILE, FileMode.Append, FileAccess.Write));
            //}
           
        }

        public void Destroy()
        {
            //if (fileStore != null)
            //{
            //    lock (_synchLock)
            //    {
            //        if (sw != null)
            //        {

            //            sw.Flush();
            //            sw.Close();
            //            sw.Dispose();
            //        }
            //        fileStore.Dispose();
            //    }
            //}
        }

        public void Debug(int code, string message)
        {
            WriteFormat(Mode.Debug, code, message);
        }

        public void Info(int code, string message)
        {
            WriteFormat(Mode.Info, code, message);
        }

        public void Warn(int code, string message)
        {
            WriteFormat(Mode.Warn, code, message);
        }

        public void Error(int code, Exception ex)
        {
            WriteFormat(Mode.Error, code, ex);
        }
        public string Read()
        {
            //this.Destroy();
            string x = StorageProviderFactory.Instance.Read(LOG_FILE);
            //this.Initialize();
            //return x;
            return x;
        }

        private void WriteFormat(Mode mode, int code, object data)
        {
            //lock (_synchLock)
            //{
            //    try
            //    {
            //        sw.WriteLine(String.Format("({0}:{1}) {2}", mode, code, data));
            //        sw.Flush();
            //    }
            //    catch
            //    {
            //        //swallow exception. 
            //    }
            //}
        }
        #endregion
    }
}
